#ifndef __Vector3_H__
#define __Vector3_H__

#include "U2PreRequest.h"
#include "U2Math.h"


U2EG_NAMESPACE_BEGIN


/** Standard 3-dimensional vector.
@remarks
    A direction in 3D space represented as distances along the 3
    orthogonal axes (x, y, z). Note that positions, directions and
    scaling factors can be represented by a vector, depending on how
    you interpret the values.
*/
class _U2Share U2Vector3
{
public:
	u2real x, y, z;

public:
    inline U2Vector3()
    {
    }

    inline U2Vector3( const u2real fX, const u2real fY, const u2real fZ )
        : x( fX ), y( fY ), z( fZ )
    {
    }

    inline explicit U2Vector3( const u2real afCoordinate[3] )
        : x( afCoordinate[0] ),
          y( afCoordinate[1] ),
          z( afCoordinate[2] )
    {
    }

    inline explicit U2Vector3( const int afCoordinate[3] )
    {
        x = (u2real)afCoordinate[0];
        y = (u2real)afCoordinate[1];
        z = (u2real)afCoordinate[2];
    }

    inline explicit U2Vector3( u2real* const r )
        : x( r[0] ), y( r[1] ), z( r[2] )
    {
    }

    inline explicit U2Vector3( const u2real scaler )
        : x( scaler )
        , y( scaler )
        , z( scaler )
    {
    }


	/** Exchange the contents of this vector with another. 
	*/
	inline void swap(U2Vector3& other)
	{
		std::swap(x, other.x);
		std::swap(y, other.y);
		std::swap(z, other.z);
	}

	inline u2real operator [] ( const size_t i ) const
    {
        assert( i < 3 );

        return *(&x+i);
    }

	inline u2real& operator [] ( const size_t i )
    {
        assert( i < 3 );

        return *(&x+i);
    }
	/// Pointer accessor for direct copying
	inline u2real* ptr()
	{
		return &x;
	}
	/// Pointer accessor for direct copying
	inline const u2real* ptr() const
	{
		return &x;
	}

    /** Assigns the value of the other vector.
        @param
            rkVector The other vector
    */
    inline U2Vector3& operator = ( const U2Vector3& rkVector )
    {
        x = rkVector.x;
        y = rkVector.y;
        z = rkVector.z;

        return *this;
    }

    inline U2Vector3& operator = ( const u2real fScaler )
    {
        x = fScaler;
        y = fScaler;
        z = fScaler;

        return *this;
    }

    inline bool operator == ( const U2Vector3& rkVector ) const
    {
        return ( x == rkVector.x && y == rkVector.y && z == rkVector.z );
    }

    inline bool operator != ( const U2Vector3& rkVector ) const
    {
        return ( x != rkVector.x || y != rkVector.y || z != rkVector.z );
    }

    // arithmetic operations
    inline U2Vector3 operator + ( const U2Vector3& rkVector ) const
    {
        return U2Vector3(
            x + rkVector.x,
            y + rkVector.y,
            z + rkVector.z);
    }

    inline U2Vector3 operator - ( const U2Vector3& rkVector ) const
    {
        return U2Vector3(
            x - rkVector.x,
            y - rkVector.y,
            z - rkVector.z);
    }

    inline U2Vector3 operator * ( const u2real fScalar ) const
    {
        return U2Vector3(
            x * fScalar,
            y * fScalar,
            z * fScalar);
    }

    inline U2Vector3 operator * ( const U2Vector3& rhs) const
    {
        return U2Vector3(
            x * rhs.x,
            y * rhs.y,
            z * rhs.z);
    }

    inline U2Vector3 operator / ( const u2real fScalar ) const
    {
        assert( fScalar != 0.0 );

        u2real fInv = 1.0f / fScalar;

        return U2Vector3(
            x * fInv,
            y * fInv,
            z * fInv);
    }

    inline U2Vector3 operator / ( const U2Vector3& rhs) const
    {
        return U2Vector3(
            x / rhs.x,
            y / rhs.y,
            z / rhs.z);
    }

    inline const U2Vector3& operator + () const
    {
        return *this;
    }

    inline U2Vector3 operator - () const
    {
        return U2Vector3(-x, -y, -z);
    }

    // overloaded operators to help U2Vector3
    inline friend U2Vector3 operator * ( const u2real fScalar, const U2Vector3& rkVector )
    {
        return U2Vector3(
            fScalar * rkVector.x,
            fScalar * rkVector.y,
            fScalar * rkVector.z);
    }

    inline friend U2Vector3 operator / ( const u2real fScalar, const U2Vector3& rkVector )
    {
        return U2Vector3(
            fScalar / rkVector.x,
            fScalar / rkVector.y,
            fScalar / rkVector.z);
    }

    inline friend U2Vector3 operator + (const U2Vector3& lhs, const u2real rhs)
    {
        return U2Vector3(
            lhs.x + rhs,
            lhs.y + rhs,
            lhs.z + rhs);
    }

    inline friend U2Vector3 operator + (const u2real lhs, const U2Vector3& rhs)
    {
        return U2Vector3(
            lhs + rhs.x,
            lhs + rhs.y,
            lhs + rhs.z);
    }

    inline friend U2Vector3 operator - (const U2Vector3& lhs, const u2real rhs)
    {
        return U2Vector3(
            lhs.x - rhs,
            lhs.y - rhs,
            lhs.z - rhs);
    }

    inline friend U2Vector3 operator - (const u2real lhs, const U2Vector3& rhs)
    {
        return U2Vector3(
            lhs - rhs.x,
            lhs - rhs.y,
            lhs - rhs.z);
    }

    // arithmetic updates
    inline U2Vector3& operator += ( const U2Vector3& rkVector )
    {
        x += rkVector.x;
        y += rkVector.y;
        z += rkVector.z;

        return *this;
    }

    inline U2Vector3& operator += ( const u2real fScalar )
    {
        x += fScalar;
        y += fScalar;
        z += fScalar;
        return *this;
    }

    inline U2Vector3& operator -= ( const U2Vector3& rkVector )
    {
        x -= rkVector.x;
        y -= rkVector.y;
        z -= rkVector.z;

        return *this;
    }

    inline U2Vector3& operator -= ( const u2real fScalar )
    {
        x -= fScalar;
        y -= fScalar;
        z -= fScalar;
        return *this;
    }

    inline U2Vector3& operator *= ( const u2real fScalar )
    {
        x *= fScalar;
        y *= fScalar;
        z *= fScalar;
        return *this;
    }

    inline U2Vector3& operator *= ( const U2Vector3& rkVector )
    {
        x *= rkVector.x;
        y *= rkVector.y;
        z *= rkVector.z;

        return *this;
    }

    inline U2Vector3& operator /= ( const u2real fScalar )
    {
        assert( fScalar != 0.0 );

        u2real fInv = 1.0f / fScalar;

        x *= fInv;
        y *= fInv;
        z *= fInv;

        return *this;
    }

    inline U2Vector3& operator /= ( const U2Vector3& rkVector )
    {
        x /= rkVector.x;
        y /= rkVector.y;
        z /= rkVector.z;

        return *this;
    }


    /** Returns the length (magnitude) of the vector.
        @warning
            This operation requires a square root and is expensive in
            terms of CPU operations. If you don't need to know the exact
            length (e.g. for just comparing lengths) use squaredLength()
            instead.
    */
    inline u2real length () const
    {
        return U2Math::Sqrt( x * x + y * y + z * z );
    }

    /** Returns the square of the length(magnitude) of the vector.
        @remarks
            This  method is for efficiency - calculating the actual
            length of a vector requires a square root, which is expensive
            in terms of the operations required. This method returns the
            square of the length of the vector, i.e. the same as the
            length but before the square root is taken. Use this if you
            want to find the longest / shortest vector without incurring
            the square root.
    */
    inline u2real squaredLength () const
    {
        return x * x + y * y + z * z;
    }

    /** Returns the distance to another vector.
        @warning
            This operation requires a square root and is expensive in
            terms of CPU operations. If you don't need to know the exact
            distance (e.g. for just comparing distances) use squaredDistance()
            instead.
    */
    inline u2real distance(const U2Vector3& rhs) const
    {
        return (*this - rhs).length();
    }

    /** Returns the square of the distance to another vector.
        @remarks
            This method is for efficiency - calculating the actual
            distance to another vector requires a square root, which is
            expensive in terms of the operations required. This method
            returns the square of the distance to another vector, i.e.
            the same as the distance but before the square root is taken.
            Use this if you want to find the longest / shortest distance
            without incurring the square root.
    */
    inline u2real squaredDistance(const U2Vector3& rhs) const
    {
        return (*this - rhs).squaredLength();
    }

    /** Calculates the dot (scalar) product of this vector with another.
        @remarks
            The dot product can be used to calculate the angle between 2
            vectors. If both are unit vectors, the dot product is the
            cosine of the angle; otherwise the dot product must be
            divided by the product of the lengths of both vectors to get
            the cosine of the angle. This result can further be used to
            calculate the distance of a point from a plane.
        @param
            vec Vector with which to calculate the dot product (together
            with this one).
        @returns
            A float representing the dot product value.
    */
    inline u2real dotProduct(const U2Vector3& vec) const
    {
        return x * vec.x + y * vec.y + z * vec.z;
    }

    /** Calculates the absolute dot (scalar) product of this vector with another.
        @remarks
            This function work similar dotProduct, except it use absolute value
            of each component of the vector to computing.
        @param
            vec Vector with which to calculate the absolute dot product (together
            with this one).
        @returns
            A u2real representing the absolute dot product value.
    */
    inline u2real absDotProduct(const U2Vector3& vec) const
    {
        return U2Math::Abs(x * vec.x) + U2Math::Abs(y * vec.y) + U2Math::Abs(z * vec.z);
    }

    /** Normalises the vector.
        @remarks
            This method normalises the vector such that it's
            length / magnitude is 1. The result is called a unit vector.
        @note
            This function will not crash for zero-sized vectors, but there
            will be no changes made to their components.
        @returns The previous length of the vector.
    */
    inline u2real normalise()
    {
        u2real fLength = U2Math::Sqrt( x * x + y * y + z * z );

        // Will also work for zero-sized vectors, but will change nothing
		// We're not using epsilons because we don't need to.
        // Read http://www.ogre3d.org/forums/viewtopic.php?f=4&t=61259
        if ( fLength > u2real(0.0f) )
        {
            u2real fInvLength = 1.0f / fLength;
            x *= fInvLength;
            y *= fInvLength;
            z *= fInvLength;
        }

        return fLength;
    }

    /** Calculates the cross-product of 2 vectors, i.e. the vector that
        lies perpendicular to them both.
        @remarks
            The cross-product is normally used to calculate the normal
            vector of a plane, by calculating the cross-product of 2
            non-equivalent vectors which lie on the plane (e.g. 2 edges
            of a triangle).
        @param
            vec Vector which, together with this one, will be used to
            calculate the cross-product.
        @returns
            A vector which is the result of the cross-product. This
            vector will <b>NOT</b> be normalised, to maximise efficiency
            - call U2Vector3::normalise on the result if you wish this to
            be done. As for which side the resultant vector will be on, the
            returned vector will be on the side from which the arc from 'this'
            to rkVector is anticlockwise, e.g. UNIT_Y.crossProduct(UNIT_Z)
            = UNIT_X, whilst UNIT_Z.crossProduct(UNIT_Y) = -UNIT_X.
			This is because OGRE uses a right-handed coordinate system.
        @par
            For a clearer explanation, look a the left and the bottom edges
            of your monitor's screen. Assume that the first vector is the
            left edge and the second vector is the bottom edge, both of
            them starting from the lower-left corner of the screen. The
            resulting vector is going to be perpendicular to both of them
            and will go <i>inside</i> the screen, towards the cathode tube
            (assuming you're using a CRT monitor, of course).
    */
    inline U2Vector3 crossProduct( const U2Vector3& rkVector ) const
    {
        return U2Vector3(
            y * rkVector.z - z * rkVector.y,
            z * rkVector.x - x * rkVector.z,
            x * rkVector.y - y * rkVector.x);
    }

    /** Returns a vector at a point half way between this and the passed
        in vector.
    */
    inline U2Vector3 midPoint( const U2Vector3& vec ) const
    {
        return U2Vector3(
            ( x + vec.x ) * 0.5f,
            ( y + vec.y ) * 0.5f,
            ( z + vec.z ) * 0.5f );
    }

    /** Returns true if the vector's scalar components are all greater
        that the ones of the vector it is compared against.
    */
    inline bool operator < ( const U2Vector3& rhs ) const
    {
        if( x < rhs.x && y < rhs.y && z < rhs.z )
            return true;
        return false;
    }

    /** Returns true if the vector's scalar components are all smaller
        that the ones of the vector it is compared against.
    */
    inline bool operator > ( const U2Vector3& rhs ) const
    {
        if( x > rhs.x && y > rhs.y && z > rhs.z )
            return true;
        return false;
    }

    /** Sets this vector's components to the minimum of its own and the
        ones of the passed in vector.
        @remarks
            'Minimum' in this case means the combination of the lowest
            value of x, y and z from both vectors. Lowest is taken just
            numerically, not magnitude, so -1 < 0.
    */
    inline void makeFloor( const U2Vector3& cmp )
    {
        if( cmp.x < x ) x = cmp.x;
        if( cmp.y < y ) y = cmp.y;
        if( cmp.z < z ) z = cmp.z;
    }

    /** Sets this vector's components to the maximum of its own and the
        ones of the passed in vector.
        @remarks
            'Maximum' in this case means the combination of the highest
            value of x, y and z from both vectors. Highest is taken just
            numerically, not magnitude, so 1 > -3.
    */
    inline void makeCeil( const U2Vector3& cmp )
    {
        if( cmp.x > x ) x = cmp.x;
        if( cmp.y > y ) y = cmp.y;
        if( cmp.z > z ) z = cmp.z;
    }

    /** Generates a vector perpendicular to this vector (eg an 'up' vector).
        @remarks
            This method will return a vector which is perpendicular to this
            vector. There are an infinite number of possibilities but this
            method will guarantee to generate one of them. If you need more
            control you should use the Quaternion class.
    */
    inline U2Vector3 perpendicular(void) const
    {
        static const u2real fSquareZero = (u2real)(1e-06 * 1e-06);

        U2Vector3 perp = this->crossProduct( U2Vector3::UNIT_X );

        // Check length
        if( perp.squaredLength() < fSquareZero )
        {
            /* This vector is the Y axis multiplied by a scalar, so we have
               to use another axis.
            */
            perp = this->crossProduct( U2Vector3::UNIT_Y );
        }
		perp.normalise();

        return perp;
    }

	/** Gets the angle between 2 vectors.
	@remarks
		Vectors do not have to be unit-length but must represent directions.
	*/
	inline Radian angleBetween(const U2Vector3& dest) const
	{
		u2real lenProduct = length() * dest.length();

		// Divide by zero check
		if(lenProduct < 1e-6f)
			lenProduct = 1e-6f;

		u2real f = dotProduct(dest) / lenProduct;

		f = U2Math::Clamp(f, (u2real)-1.0, (u2real)1.0);
		return U2Math::ACos(f);

	}

    /** Returns true if this vector is zero length. */
    inline bool isZeroLength(void) const
    {
        u2real sqlen = (x * x) + (y * y) + (z * z);
        return (sqlen < (1e-06 * 1e-06));

    }

    /** As normalise, except that this vector is unaffected and the
        normalised vector is returned as a copy. */
    inline U2Vector3 normalisedCopy(void) const
    {
        U2Vector3 ret = *this;
        ret.normalise();
        return ret;
    }

    /** Calculates a reflection vector to the plane with the given normal .
    @remarks NB assumes 'this' is pointing AWAY FROM the plane, invert if it is not.
    */
    inline U2Vector3 reflect(const U2Vector3& normal) const
    {
        return U2Vector3( *this - ( 2 * this->dotProduct(normal) * normal ) );
    }

	/** Returns whether this vector is within a positional tolerance
		of another vector.
	@param rhs The vector to compare with
	@param tolerance The amount that each element of the vector may vary by
		and still be considered equal
	*/
	inline bool positionEquals(const U2Vector3& rhs, u2real tolerance = 1e-03) const
	{
		return U2Math::RealEqual(x, rhs.x, tolerance) &&
			U2Math::RealEqual(y, rhs.y, tolerance) &&
			U2Math::RealEqual(z, rhs.z, tolerance);

	}

	/** Returns whether this vector is within a positional tolerance
		of another vector, also take scale of the vectors into account.
	@param rhs The vector to compare with
	@param tolerance The amount (related to the scale of vectors) that distance
        of the vector may vary by and still be considered close
	*/
	inline bool positionCloses(const U2Vector3& rhs, u2real tolerance = 1e-03f) const
	{
		return squaredDistance(rhs) <=
            (squaredLength() + rhs.squaredLength()) * tolerance;
	}

	/** Returns whether this vector is within a directional tolerance
		of another vector.
	@param rhs The vector to compare with
	@param tolerance The maximum angle by which the vectors may vary and
		still be considered equal
	@note Both vectors should be normalised.
	*/
	inline bool directionEquals(const U2Vector3& rhs,
		const Radian& tolerance) const
	{
		u2real dot = dotProduct(rhs);
		Radian angle = U2Math::ACos(dot);

		return U2Math::Abs(angle.valueRadians()) <= tolerance.valueRadians();

	}

	/// Check whether this vector contains valid values
	inline bool isNaN() const
	{
		return U2Math::isNaN(x) || U2Math::isNaN(y) || U2Math::isNaN(z);
	}

	/// Extract the primary (dominant) axis from this direction vector
	inline U2Vector3 primaryAxis() const
	{
		u2real absx = U2Math::Abs(x);
		u2real absy = U2Math::Abs(y);
		u2real absz = U2Math::Abs(z);
		if (absx > absy)
			if (absx > absz)
				return x > 0 ? U2Vector3::UNIT_X : U2Vector3::NEGATIVE_UNIT_X;
			else
				return z > 0 ? U2Vector3::UNIT_Z : U2Vector3::NEGATIVE_UNIT_Z;
		else // absx <= absy
			if (absy > absz)
				return y > 0 ? U2Vector3::UNIT_Y : U2Vector3::NEGATIVE_UNIT_Y;
			else
				return z > 0 ? U2Vector3::UNIT_Z : U2Vector3::NEGATIVE_UNIT_Z;


	}

	// special points
    static const U2Vector3 ZERO;
    static const U2Vector3 UNIT_X;
    static const U2Vector3 UNIT_Y;
    static const U2Vector3 UNIT_Z;
    static const U2Vector3 NEGATIVE_UNIT_X;
    static const U2Vector3 NEGATIVE_UNIT_Y;
    static const U2Vector3 NEGATIVE_UNIT_Z;
    static const U2Vector3 UNIT_SCALE;

    /** Function for writing to a stream.
    */
    inline _U2Share friend std::ostream& operator <<
        ( std::ostream& o, const U2Vector3& v )
    {
        o << "U2Vector3(" << v.x << ", " << v.y << ", " << v.z << ")";
        return o;
    }
};


U2EG_NAMESPACE_END


#endif
